package com.ytd.common.util;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.webkit.MimeTypeMap;

import com.ytd.common.base.BaseApplication;
import com.ytd.common.bean.DownloadModel;
import com.ytd.common.net.RequestManager;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class DownloadManagerUtil {
    private static DownloadManagerUtil mdow;
    private DownloadManager dm;

    private DownloadManagerUtil(Context context) {
        dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    }

    public static DownloadManagerUtil getInstance(Context context) {
        if (mdow == null) {
            synchronized (DownloadManagerUtil.class) {
                if (mdow == null) {
                    mdow = new DownloadManagerUtil(context);
                    return mdow;
                }
            }
        }
        return mdow;
    }

    private DownloadModel downloadModel;
    private DownloadManager.Request request;

    public DownloadManagerUtil setUrl(String url, long appSize) {
        String[] str = url.split("/");
        downloadModel = new DownloadModel();
        downloadModel.setUrl(url);
        downloadModel.setSize(appSize);
        downloadModel.setFileName(str[str.length - 1]);
        request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedOverRoaming(true);//漫游网络是否可以下载
        //设置文件类型，可以在下载结束后自动打开该文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        request.setMimeType(mimeString);
        return this;
    }

    public DownloadManagerUtil setVisible(boolean isvisible) {
        if (isvisible) {
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            request.setVisibleInDownloadsUi(true);
        } else {
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            request.setVisibleInDownloadsUi(false);
        }

        return this;
    }

    public DownloadManagerUtil setPublicDir(String dirName) {
        request.setDestinationInExternalPublicDir(dirName, downloadModel.getFileName());
        //   request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,downloadModel.getFileName());
        downloadModel.setPath(FileUtils.SdDirectory + "/" + dirName + "/" + downloadModel.getFileName());
        return this;
    }

    public DownloadManagerUtil setPrivateDir(String dirName) {
        request.setDestinationInExternalFilesDir(BaseApplication.getContext(), dirName, downloadModel.getFileName());
        downloadModel.setPath(
            BaseApplication.getContext().getExternalFilesDir(dirName).getPath() + "/" + downloadModel.getFileName());
        return this;
    }

    public DownloadModel getModel() {
        FileUtils.deleteQuietly(new File(downloadModel.getPath()));
        downloadModel.setId(dm.enqueue(request));
        return downloadModel;
    }

    /**
     * 获取下载百分比
     *
     * @param downloadId
     * @return
     */
    public int getDownloadPercent(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = dm.query(query);
        if (c.moveToFirst()) {
            int downloadBytesIdx = c.getColumnIndexOrThrow(
                DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            int totalBytesIdx = c.getColumnIndexOrThrow(
                DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            long totalBytes = c.getLong(totalBytesIdx);
            long downloadBytes = c.getLong(downloadBytesIdx);
            return (int) (downloadBytes * 100 / totalBytes);
        }
        return 0;
    }

    public static void httpDown(final String urlPath, String savePath) {
        URL url;
        HttpURLConnection connection;
        try {
            //统一资源
            url = new URL(urlPath);
            //打开链接
            connection = (HttpURLConnection) url.openConnection();
            //设置链接超时
            connection.setConnectTimeout(4000);
            connection.setReadTimeout(4000);
            //设置请求方法
            connection.setRequestMethod("GET");
            //设置请求的字符编码
            connection.setRequestProperty("ContentType", "application/octet-stream");
            connection.setRequestProperty("content-disposition", "attachment");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("Accept-Encoding", "identity");
            connection.setRequestProperty("Connection", "Keep-Alive");  //设置connection的方式
            //设置connection打开链接资源
            connection.connect();
            //创建一个文件对象用于存储下载的文件 此次的getFilesDir()方法只有在继承至Context类的类中
            // 可以直接调用其他类中必须通过Context对象才能调用，得到的是内部存储中此应用包名下的文件路径
            //如果使用外部存储的话需要添加文件读写权限，5.0以上的系统需要动态获取权限 此处不在不做过多说明。
            File file = new File(savePath);
            //创建一个文件输出流
            FileOutputStream outputStream = new FileOutputStream(file);
            //得到链接的响应码 200为成功
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到服务器响应的输入流
                InputStream inputStream = connection.getInputStream();
                //获取请求的内容总长度
                int contentLength = connection.getContentLength();
                //创建缓冲输入流对象，相对于inputStream效率要高一些
                BufferedInputStream bfi = new BufferedInputStream(inputStream);
                //此处的len表示每次循环读取的内容长度
                int len;
                //已经读取的总长度
                int totle = 0;
                //bytes是用于存储每次读取出来的内容
                byte[] bytes = new byte[1024];
                while ((len = bfi.read(bytes)) != -1) {
                    //每次读取完了都将len累加在totle里
                    totle += len;
                    //通过文件输出流写入从服务器中读取的数据
                    outputStream.write(bytes, 0, len);
                }
                //关闭打开的流对象
                outputStream.close();
                inputStream.close();
                bfi.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean checkFile() {
        long size = YtdConfig.getModel().getSize();
        if (size == 0) {
            return true;
        }
        String path = YtdConfig.getModel().getPath();
        File file = new File(path);
        if (file.exists()) {
            long length = file.length();
            LogUtil.d("download File :" + length + "--appSze:" + size);
            return length == size;
        }
        return false;
    }

    public static void reDownload() {
        RequestManager.download(YtdConfig.getModel().getUrl(), 0);
    }
}
